import { defineNuxtPlugin } from '#app';

const customDirective = {
  mounted(el: HTMLElement, binding: { value: boolean | string }) {
    if (!(binding.value ?? true)) return
    let imgElements: HTMLElement[] = [];

    if (el.tagName === 'IMG') {
      imgElements = [el];
    } else {
      imgElements = Array.from(el.querySelectorAll('img'));
    }

    const observer = (img: HTMLElement) => {
      if (typeof binding.value === 'string') {
        const aspectRatios: number[] = binding.value.split('/').map((item) => Number(item));
        // img.style.height = 'auto';
        const w = img.clientWidth / (aspectRatios[0] as number);
        img.style.height = w * (aspectRatios[1] as number) + 'px';
      } else {
        img.style.height = 'auto';
      }
      img.style.aspectRatio = '1 / 1';
    }

    // 初始化图片样式
    imgElements.forEach((img: HTMLElement) => {
      img.style.width = '100%';
      observer(img)
    });

    // 监听元素尺寸变化
    const resizeObserver = new ResizeObserver(() => {
      imgElements.forEach((img: HTMLElement) => {
        observer(img)
      });
    });

    // 开始监听目标元素
    resizeObserver.observe(el);

    // 保存观察者实例，以便在卸载时清理
    (el as any).__imgAutoResizeObserver__ = resizeObserver;
  },

  unmounted(el: HTMLElement) {
    // 清理 ResizeObserver 以避免内存泄漏
    const observer = (el as any).__imgAutoResizeObserver__;
    if (observer) {
      observer.disconnect();
      delete (el as any).__imgAutoResizeObserver__;
    }
  },
};

const hoverPopDirective = { 
    mounted(el: HTMLElement) { 
        el.style.transition = 'transform 0.3s ease, box-shadow 0.3s ease'; 
        // 设置鼠标悬停时为手势样式 
        el.style.cursor = 'pointer'; 
        
        const handleMouseEnter = () => { 
            el.style.transform = 'translateY(-5px)'; 
            el.style.boxShadow = '0 5px 15px rgba(0, 0, 0, 0.2)'; 
        }; 

        const handleMouseLeave = () => { 
            el.style.transform = ''; 
            el.style.boxShadow = ''; 
        }; 

        el.addEventListener('mouseenter', handleMouseEnter); 
        el.addEventListener('mouseleave', handleMouseLeave); 

        // 保存事件处理函数，以便在卸载时移除 
        (el as any).__mouseEnterHandler__ = handleMouseEnter; 
        (el as any).__mouseLeaveHandler__ = handleMouseLeave; 
    }, 
    unmounted(el: HTMLElement) { 
        // 移除事件监听器以避免内存泄漏 
        const mouseEnterHandler = (el as any).__mouseEnterHandler__; 
        const mouseLeaveHandler = (el as any).__mouseLeaveHandler__; 
        if (mouseEnterHandler) el.removeEventListener('mouseenter', mouseEnterHandler); 
        if (mouseLeaveHandler) el.removeEventListener('mouseleave', mouseLeaveHandler); 
        
        delete (el as any).__mouseEnterHandler__; 
        delete (el as any).__mouseLeaveHandler__; 
    } 
}; 

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.directive('img-auto', customDirective);
  nuxtApp.vueApp.directive('hover-pop', hoverPopDirective);
});